<template>
    <div class="sample">
        <div class="header">
            <van-nav-bar title="填写单号" left-arrow @click-left="handleLeft">
            </van-nav-bar>
        </div>
        <div class="sample_form">
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field name="trackingNumber" label="快递单号" v-model="queryParams.expressNumber" placeholder="请输入"
                        @input="handleTrackingNumberChange" :rules="[
                            { required: true, trigger: 'onBlur', message: '请输入快递单号' },
                            {
                                validator: validatorNumber,
                                message: '请输入正确的快递单号',
                            },
                        ]">
                        <template #button>
                            <van-button size="small" color="#70BAFF" :loading="loading" loading-text="识别中..." plain
                                style="width: 70px;font-weight: bold;" @click="getLogisticsOcr">识别</van-button>
                        </template>

                    </van-field>
                </van-cell-group>
                <van-cell-group inset>
                    <van-field name="shippingCompany" label="快递公司" v-model="queryParams.expressCompany" is-link readonly
                        :placeholder="returnShippingCompanyColumns.length > 1 ? '请选择' : '自动识别'"
                        @click="deliveryStatusClick"
                        :rules="[{ required: true, trigger: 'onBlur', message: '请选择快递公司' }]" />
                    <van-popup v-model:show="showReturnShippingCompany" position="bottom">
                        <van-picker :columns="returnShippingCompanyColumns" @confirm="onConfirmReturnShippingCompany"
                            @cancel="showReturnShippingCompany = false" />
                    </van-popup>
                    <div v-if="remindStatus" style="margin-left: 15px;margin-top:20px;border: none"><van-icon
                            name="warning" style="color: #FF6E00;margin-right: 10px" /><span style="color: #6F6F6F">{{
                                remindStatusText ?
                                    '识别到多个物流/快递公司,请确认' : '未查询到物流/快递公司,请核对单号' }}</span></div>
                </van-cell-group>

                <!--          <div style="margin-left: 15px"><van-icon name="warning" style="color: #FF6E00;margin-right: 10px"/><span style="color: #6F6F6F">{{'未查询到物流/快递公司'}}</span></div>-->
                <div style="position: fixed;width: 100%;bottom: 0;display: flex;justify-content: space-between;"
                    class="btn_box">
                    <van-button round block type="primary" @click='onsubtg'>
                        跳过
                    </van-button>
                    <van-button round block :loading="loading" loading-text="执行中..." type="primary" native-type="submit"
                        v-throttle:click>
                        保存
                    </van-button>
                </div>
            </van-form>
        </div>

    </div>
</template>
<script setup lang="ts">
import { computed, ref } from 'vue';
import { skipExpress, addExpress } from '@/api/productHome/index'
import { getDeliveryInfo } from '@/api/productList/index'
import { showSuccessToast, showFailToast } from 'vant';
import { useRoute, useRouter } from 'vue-router';
import { showConfirmDialog } from "vant";
const router = useRouter()
const route = useRoute()
const queryParams = ref({
    expressCompany: '',
    shippingCompany: '',
    expressNumber: '',
    logisticsTraceDetailList: [],
    logisticsType: ''
})
const loading = ref(false)
const validatorNumber = (val) => /^(?![a-zA-Z]+$)[a-zA-Z0-9]{8,30}$/.test(val);

/** 商品id */
const uniquekey = computed(() => {
    return route.params.id
})

const productId = computed(() => {
    return route.query.productId
})

// 定义 Column 类型
interface Column {
    text: string;
    value: string;
    logisticsTraceDetailList: any[];
    logisticsType: string;
}
const showReturnShippingCompany = ref(false)
const returnShippingCompanyColumns = ref<Column[]>([

])

/** 快递公司 */
const getDiscountPrice = async () => {
    // const res = await getDicts('hm_express')
    // res.data.forEach(element => {
    //     element.text = element.dictLabel
    //     element.value = element.dictValue
    // })
    // returnShippingCompanyColumns.value = res.data
}
getDiscountPrice()
/** 快递公司关闭 */
const onConfirmReturnShippingCompany = ({ selectedOptions }) => {
    queryParams.value.expressCompany = selectedOptions[0]?.text;
    queryParams.value.shippingCompany = selectedOptions[0]?.text;
    queryParams.value.logisticsTraceDetailList = selectedOptions[0]?.logisticsTraceDetailList;
    queryParams.value.logisticsType = selectedOptions[0]?.logisticsType;
    showReturnShippingCompany.value = false;
}

//跳过
const onsubtg = async () => {
    showConfirmDialog({
        message: "跳过邮寄状态的商品将被视为已实际收到样品，请确保您已收到样品~",
    }).then(async () => {
        const res = await skipExpress({ id: uniquekey.value, productId: productId.value });
        if (res.code === 200) {
            showSuccessToast({ type: 'success', message: '跳过成功' });
            router.back()
        }
    });
    return false;
}

/** 保存 */
const onSubmit = async () => {
    if (returnShippingCompanyColumns.value.length > 1) {

    }
    loading.value = true
    try {
        await addExpress({ ...queryParams.value, id: uniquekey.value, productId: productId.value, trackingNumber: queryParams.value.expressNumber });
        loading.value = false
        showSuccessToast({ type: 'success', message: '填写单号成功' });
        router.back()
    } catch (error) {
        if (error == 'timeout') {
            showFailToast('填写单号失败');
        }
        loading.value = false
    }
}

//提醒状态和文字
const remindStatus = ref(false)
const remindStatusText = ref(true)

//快递识别
const getLogisticsOcr = async () => {
    remindStatus.value = false
    loading.value = true
    try {
        if (queryParams.value.expressNumber) {

        }
        queryParams.value.expressCompany = ''
        queryParams.value.logisticsType = ''
        queryParams.value.logisticsTraceDetailList = []
        returnShippingCompanyColumns.value = []
        //获取快递信息如果有多条就需要选择在保存
        let deliveryInfo = {
            orderNo: queryParams.value.expressNumber
        }
        const res = await getDeliveryInfo(deliveryInfo)
        loading.value = false
        if (res.code != 200 || res.data == null) {
            // showFailToast({ type: 'fail', message: '该订单号未查询到物流信息' });
            remindStatus.value = true
            remindStatusText.value = false
            return
        }
        //如果有多条需要人工手动选择
        if (res.data.info.length >= 2) {
            res.data.info.forEach(element => {
                let ele: Column = {
                    text: element.logisticsCompanyName || element.cpCode,  // 设置默认值
                    value: element.cpCode,  // 设置默认值
                    logisticsTraceDetailList: element.logisticsTraceDetailList || [],
                    logisticsType: element.cpCode
                };
                returnShippingCompanyColumns.value.push(ele);
                // showFailToast({ type: 'fail', message: '快递存在多条,请手动选择' });
            });
            remindStatus.value = true
            remindStatusText.value = true
        } else {
            queryParams.value.expressCompany = res.data.info[0].logisticsCompanyName || res.data.info[0].cpCode
            queryParams.value.shippingCompany = res.data.info[0].logisticsCompanyName || res.data.info[0].cpCode
            queryParams.value.logisticsTraceDetailList = res.data.info[0].logisticsTraceDetailList || []
            queryParams.value.logisticsType = res.data.info[0].cpCode
        }
    } catch (error) {
        if (error == 'timeout') {
            showFailToast('识别失败');
        }
        loading.value = false
    }
}

//快递公司点击
const deliveryStatusClick = async () => {
    if (returnShippingCompanyColumns.value.length > 1) {
        showReturnShippingCompany.value = true
    }
}

//订单号发生变化清除缓存数据
const handleTrackingNumberChange = async () => {
    queryParams.value.expressCompany = ''
    queryParams.value.logisticsType = ''
    queryParams.value.logisticsTraceDetailList = []
    remindStatus.value = false
    returnShippingCompanyColumns.value = []
}
/** 返回区分不同地址 */
const handleLeft = () => {
    router.back();
};

</script>
<style lang="less" scoped>
.btn_box button {
    border-radius: 0 !important;
}

.btn_box button:nth-child(1) {
    background-color: #fff !important;
    color: var(--van-button-primary-background) !important;
    border-color: #fff !important;
}

.sample {
    background-color: #F6FAFF;
    width: 100%;
    height: calc(100vh);
    display: flex;
    flex-flow: column;

    .header {
        background: linear-gradient(#CDECFF 0%, #FFFFFF 70%);
        filter: blur(0px);
        height: 90px;
        padding-top: 44px;
        box-sizing: border-box;
        width: 100%;
        position: fixed;
        z-index: 6003;

        :deep(.van-icon-arrow-left) {
            color: #1a1b1c !important;
        }

        :deep(.van-nav-bar) {
            background: none !important;
        }

        :deep(.van-nav-bar__content) {
            background-color: transparent !important;
        }
    }

    .sample_form {
        flex: 1;
        min-height: 0;
        padding: 100px 0;
    }
}

:deep(.van-cell-group--inset) {
    margin: 0 !important;
    border-radius: 0 !important;
}

:deep(.van-form) {
    padding-bottom: 35px !important;
}
</style>